require('dotenv').config();
const express = require('express');
const cors = require('cors');
const apiRoutes = require('./routes/api-route');
const path = require('path');

const app = express();

// 中间件
const corsOptions = {
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));

app.use(express.json());
app.use((req, res, next) => {
  console.log(`Incoming request: ${req.method} ${req.url}`);
  next();
});

// 静态文件服务 - 用于访问上传的文件
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// 路由
app.use('/api', apiRoutes);

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Server error' });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});